using Render;

namespace Noise
{
    public static class GradientArray
    {
        private static float IntToFloat(int i)
        {
            return Colors.IntToFloat(i)*2.0f-1.0f;
        }

        private static int FloatToInt(float f)
        {
            return Colors.FloatToInt(f*0.5f+0.5f);
        }

        public static uint[] Grad2(int width, int height)
        {
            int p0, p1;
            int g0x, g0y, g1x, g1y;

            uint[] gradients = new uint[width*height];

            // Store a gradient vector for each perm value
            for (int h=0; h<height; h++)
            {
                for (int w=0; w<width; w++)
                {
                    // Wrap perm values at 255
                    p0 = w&255;
                    p1 = h&255;

                    // Get gradient components
                    Gradient.Grad2(p0, out g0x, out g0y);
                    Gradient.Grad2(p1, out g1x, out g1y);

                    // Convert to color components
                    g0x = FloatToInt(g0x);
                    g0y = FloatToInt(g0y);
                    g1x = FloatToInt(g1x);
                    g1y = FloatToInt(g1y);

                    gradients[(h*width)+w] = Colors.UInt32FromRGBA(g0x, g0y, g1x, g1y);
                }
            }

            return gradients;
        }

        public static uint[] PermGrad3(int width)
        {
            int p;
            int gx, gy, gz, gw;

            uint[] gradients = new uint[width];

            // Store a gradient vector for each perm value
            for (int w=0; w<width; w++)
            {
                // Wrap perm values at 255
                p = w&255;

                // Permutate value once more
                p = Permutation.Perm1(p);

                // Get gradient components
                Gradient.Grad3(p, out gx, out gy, out gz);

                // Convert to color components
                gx = FloatToInt(gx);
                gy = FloatToInt(gy);
                gz = FloatToInt(gz);
                gw = FloatToInt(0);

                gradients[w] = Colors.UInt32FromRGBA(gx, gy, gz, gw);
            }

            return gradients;
        }
    }
}